package com.yc.vote.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yc.vote.entity.User;
import com.yc.vote.entity.Vote;
import com.yc.vote.mapper.VoteMapper;
import javax.annotation.Resource;

import com.yc.vote.service.BizException;
import com.yc.vote.service.IVoteService;
import com.yc.vote.vo.Result;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 投票系统-题目表-2 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/vote/vote")
public class VoteController {

    @Resource
    VoteMapper voteMapper;

    @RequestMapping("query")
    public Map<String,Object> query(String vname,
                            @RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "5") int size){
//        Page<Vote> p = new Page<>(page,size);
        // PageHelper 必須在查詢方法前一行代碼執行分页设置
        Page<Object> p = PageHelper.startPage(page, size);
        // pagehelper 通过插件在后台直接获取到数据, 设置到 p 中
        voteMapper.selectLikeVname(vname);
        Map<String,Object> res = new HashMap<>();
        res.put("total", p.getTotal());
        res.put("rows", p);
        return res;
    }

    //MyBatisPlus 分页查询
    @RequestMapping("query1")
    public IPage<Vote> query1(String vname,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "5") int size){
        IPage<Vote> p = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,size);
        return voteMapper.selectLikeVname(vname,p);
    }

    @Resource
    IVoteService voteService;

    @RequestMapping("create")
    public Result create(
            @RequestBody Vote vote,
            @SessionAttribute User loginedUser)
            // BizException 在哪里捕获
            throws BizException {
        // 设置用户id
        vote.setUsid(loginedUser.getId());
        voteService.create(vote);
        return new Result(1,"添加投票成功",vote);
    }

    @RequestMapping("find")
    public Vote find(int id){
        return voteMapper.selectById(id);
    }

    @RequestMapping("del")
    public Result delById(int id) throws BizException {
        voteService.delById(id);
        return new Result(1,"删除投票成功!",null);
    }
}

